#!/bin/bash

# 使脚本以管理员权限运行
if [ "$(id -u)" -ne "0" ]; then
    echo "请使用管理员权限运行此脚本。"
    exit 1
fi

echo "开始初始化脚本..."

# 1. 更换镜像源为清华大学镜像
echo "更换镜像源为清华大学镜像..."
cat <<EOL > /etc/apt/sources.list
# 默认注释掉原有源
# deb http://archive.ubuntu.com/ubuntu/ $(lsb_release -cs) main restricted universe multiverse
# deb http://archive.ubuntu.com/ubuntu/ $(lsb_release -cs)-updates main restricted universe multiverse
# deb http://archive.ubuntu.com/ubuntu/ $(lsb_release -cs)-backports main restricted universe multiverse
# deb http://security.ubuntu.com/ubuntu $(lsb_release -cs)-security main restricted universe multiverse

# 清华大学镜像源
deb https://mirrors.tuna.tsinghua.edu.cn/ubuntu/ $(lsb_release -cs) main restricted universe multiverse
deb https://mirrors.tuna.tsinghua.edu.cn/ubuntu/ $(lsb_release -cs)-updates main restricted universe multiverse
deb https://mirrors.tuna.tsinghua.edu.cn/ubuntu/ $(lsb_release -cs)-backports main restricted universe multiverse
deb https://mirrors.tuna.tsinghua.edu.cn/ubuntu/ $(lsb_release -cs)-security main restricted universe multiverse
EOL

echo "更新软件包列表..."
apt update

# 2. 检查并安装 openssh-server
echo "检查并安装 openssh-server..."
if dpkg -l | grep -q openssh-server; then
    echo "openssh-server 已安装。"
else
    echo "openssh-server 未安装，正在安装..."
    apt install -y openssh-server
fi

# 启动并启用 SSH 服务
echo "启动并启用 SSH 服务..."
systemctl start ssh
systemctl enable ssh

# 重新加载系统服务单元配置
echo "重新加载系统服务单元配置..."
systemctl daemon-reload

# 3. 永久关闭防火墙（ufw）
echo "永久关闭防火墙（ufw）..."
ufw status | grep -q "Status: inactive"
if [ $? -ne 0 ]; then
    ufw disable --force
    echo "防火墙（ufw）已永久关闭。"
else
    echo "防火墙（ufw）已经关闭。"
fi

# 4. 检查并关闭 SELinux
echo "检查 SELinux 状态..."
if command -v sestatus >/dev/null 2>&1; then
    SELINUX_STATUS=$(sestatus | grep "SELinux status" | awk '{print $3}')
    if [ "$SELINUX_STATUS" = "enabled" ]; then
        echo "SELinux 已启用，正在禁用 SELinux..."
        
        # 修改 SELinux 配置文件
        sed -i 's/^SELINUX=.*$/SELINUX=disabled/' /etc/selinux/config
        
        # 需要重启系统以使更改生效
        echo "已将 SELinux 配置为禁用。请重新启动系统以使更改生效。"
    else
        echo "SELinux 已经禁用。"
    fi
else
    echo "SELinux 工具未安装。"
fi

# 5. 配置 SSH 允许 root 用户远程登录
echo "配置 SSH 允许 root 用户远程登录..."
SSHD_CONFIG="/etc/ssh/sshd_config"

if grep -q "^PermitRootLogin" "$SSHD_CONFIG"; then
    sed -i 's/^PermitRootLogin .*/PermitRootLogin yes/' "$SSHD_CONFIG"
else
    echo "PermitRootLogin yes" >> "$SSHD_CONFIG"
fi

# 重启 SSH 服务以应用更改
echo "重启 SSH 服务..."
systemctl restart ssh

# 6. 时间同步
echo "安装并启动系统时间同步服务..."
apt install -y systemd-timesyncd
systemctl start systemd-timesyncd
systemctl enable systemd-timesyncd

echo "初始化脚本完成。"